<?php
 /**
 *  +---------------------------------------------------------------------- 
 *  | 文件功能：用户功能相关控制器
 *  +---------------------------------------------------------------------- 
 *  | Copyright (c) 2022~2024 https://www.huihuiv.com All rights reserved.
 *  +---------------------------------------------------------------------- 
 *  | Create At: 2024年02月26日 18:07:03
 *  +---------------------------------------------------------------------- 
 *  | Author: 半壶水 <star@cqshanwen.com>
 *  +---------------------------------------------------------------------- 
 */

namespace App\Http\Controllers\Api;

use App\Interface\CurdController;
use App\Librarys\Message;
use App\Librarys\Sort;
use App\Models\AuthModel;
use App\Models\GroupModel;
use App\Models\User;
use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class UserController extends BaseController implements CurdController
{
    private Request $request;
    private Model $userModel;
    private Model $groupModel;
    private Model $authModel;

    public function __construct(Request $request, User $userModel, GroupModel $groupModel, AuthModel $authModel)
    {
        $this->request = $request;
        $this->userModel = $userModel;
        $this->groupModel = $groupModel;
        $this->authModel = $authModel;
    }

    /**
     * 用户普通常规注册方法
     *
     * @return JsonResponse
     */
    public function register(): JsonResponse
    {
        // 获取注册基础信息
        $userInfo['phone'] = $this->request->phone;
        $userInfo['username'] = $this->request->username;
        $userInfo['password'] = $this->request->password;
        $userInfo['password_confirmation'] = $this->request->repassword;

        // 验证信息
        $validate = Validator::make($userInfo, [
            'phone' => 'required|unique:sw_user',
            'username' => 'required|unique:sw_user',
            'password' => 'required|confirmed',
            'password_confirmation' => 'required'
        ], [
            'phone.required' => '手机号码不能为空',
            'phone.unique' => '手机号码已被使用，请尝试找回密码',
            'username.required' => '用户名不能为空',
            'username.unique' => '用户名已经存在，请尝试更换再试',
            'password.required' => '登录密码不能为空',
            'password.confirmed' => '两次登录密码输入不一致'
        ]);

        // 判断验证是否通过
        if ($validate->fails()) {
            // 验证不通过，返回错误，终止执行
            return Message::show(false, $validate->errors()->first());
        }

        // 密码进行加密操作
        $userInfo['password'] = Hash::make($userInfo['password']);

        // 验证通过，继续执行,开启事务
        DB::beginTransaction();
        try {
            // 尝试写入数据
            $this->userModel->create($userInfo);
            // 提交事务
            DB::commit();
            // 写入成功
            return Message::show(true, '用户注册成功，请登录...');
        } catch (Exception $error) {
            // 写入期间发生异常，写入失败，回滚事务
            DB::rollBack();
            return Message::show(false, '用户注册失败：' . $error->getMessage());
        }
    }

    /**
     * 用户普通常规登录方法
     *
     * @return JsonResponse
     */
    public function login(): JsonResponse
    {
        // 获取登录所需必要参数
        $userInfo['phone'] = $this->request->phone;
        $userInfo['password'] = $this->request->password;

        // 必要参数条件验证
        $validate = Validator::make($userInfo, [
            'phone' => 'required',
            'password' => 'required'
        ], [
            'phone.required' => '手机号码不能为空',
            'password.required' => '登录密码不能为空'
        ]);

        // 判断验证是否通过
        if ($validate->fails()) {
            // 判断未通过
            return Message::show(false, $validate->errors()->first());
        }

        // 判断通过，进行用户信息比对，并生成TOKEN
        $token = Auth::guard('api')->attempt($userInfo);

        // 判断TOKEN是否有效
        if (!$token) {
            // 登录信息不符合，TOKEN信息无效
            return Message::show(false, '手机号码或者密码错误，请重试');
        }

        // 登录信息符合，返回TOKEN信息
        return Message::token(true, '登录成功', $token);
    }

    /**
     * 更新/刷新token
     *
     * @return JsonResponse
     */
    public function refresh_token(): JsonResponse
    {
        // 刷新token
        $token = Auth::guard('api')->refresh();
        return Message::token(true, '刷新成功', $token);
    }

    /**
     * 注销/退出登录
     *
     * @return JsonResponse
     */
    public function logout(): JsonResponse
    {
        // 注销登录
        Auth::guard('api')->logout();
        return Message::show(true, '注销登录');
    }

    /**
     * 获取当前登录信息
     *
     * @return JsonResponse
     */
    public function get_self_info(): JsonResponse
    {
        // 获取个人基础信息
        $self = Auth::guard('api')->user();

        // 获取用户组信息
        $selfGroup = $this->groupModel->where(['gid' => $self->gid])->first();

        // 获取用户组权限列表
        $slefRights = $selfGroup->rights;
        $slefRights = json_decode($slefRights);

        // 获取用户所有权限列表详情
        $slefRightsList = $this->authModel->whereIn('auth_id', $slefRights)->where(['is_hidden' => '0'])->get();

        // 生成用户权限列表树信息
        $selfRightsListTree = Sort::build_auth_tree(0, $slefRightsList);

        // 组装数据
        $userInfo['user_info'] = $self;
        $userInfo['auth_menus'] = $selfRightsListTree;

        return Message::show(true, '获取成功', $userInfo);
    }

    /**
     * 手动创建用户
     *
     * @return void
     */
    public function create()
    {
        // 获取操作标识
        $flag = $this->request->flag;
        // switch匹配操作方法
        switch ($flag) {
            default:
                return Message::show(false, '未定义操作');
                break;
            case 'manager':
                // 管理员后台手动添加
                // 获取必要参数
                $userInfo['username'] = $this->request->username;
                $userInfo['phone'] = $this->request->phone;
                $userInfo['status'] = $this->request->status;
                $userInfo['gid'] = $this->request->gid;
                $userInfo['password'] = $this->request->password;
                $userInfo['password_confirmation'] = $this->request->repassword;

                // 验证数据
                $validate = Validator::make($userInfo, [
                    'phone' => 'required|unique:sw_user',
                    'username' => 'required|unique:sw_user',
                    'gid' => 'required',
                    'password' => 'required|confirmed',
                    'password_confirmation' => 'required'
                ], [
                    'phone.required' => '手机号码不能为空',
                    'phone.unique' => '手机号码已被使用，请尝试找回密码',
                    'username.required' => '用户名不能为空',
                    'username.unique' => '用户名已经存在，请尝试更换再试',
                    'gid.required' => '用户组不能为空',
                    'password.required' => '登录密码不能为空',
                    'password.confirmed' => '两次登录密码输入不一致'
                ]);

                // 判断是否验证通过
                if ($validate->fails()) {
                    // 验证失败
                    return Message::show(false, $validate->errors()->first());
                }

                // 密码加密
                $userInfo['password'] = Hash::make($userInfo['password']);

                // 验证通过，开启事务
                DB::beginTransaction();
                try {
                    // 写入数据
                    $this->userModel->create($userInfo);
                    // 提交事务
                    DB::commit();
                    return Message::show(true, '用户新增成功');
                } catch (Exception $error) {
                    // 事务回滚
                    DB::rollBack();
                    return Message::show(false, $error->getMessage());
                }
                break;
            case 'update':
                // 更改用户信息
                // 获取必要参数
                $userInfo['username'] = $this->request->username;
                $userInfo['phone'] = $this->request->phone;
                $userInfo['status'] = $this->request->status;
                $userInfo['gid'] = $this->request->gid;
                $userInfo['uid'] = $this->request->uid;
                $password = $this->request->password;

                // 判断是否更改密码
                if ($password == '' || $password == null) {
                    // 不更改密码
                    // 验证数据
                    $validate = Validator::make($userInfo, [
                        'uid' => 'required',
                        'phone' => 'required',
                        'username' => 'required',
                        'gid' => 'required',
                    ], [
                        'uid.required' => '确实必要更新条件',
                        'phone.required' => '手机号码不能为空',
                        'username.required' => '用户名不能为空',
                        'gid.required' => '用户组不能为空',
                    ]);

                    // 判断验证结构
                    if ($validate->fails()) {
                        // 验证失败
                        return Message::show(false, $validate->errors()->first());
                    }
                } else {
                    // 要更改密码,获取密码参数
                    $userInfo['password'] = $this->request->password;
                    $repassword = $this->request->repassword;

                    // 验证数据
                    $validate = Validator::make($userInfo, [
                        'uid' => 'required',
                        'phone' => 'required',
                        'username' => 'required',
                        'gid' => 'required',
                        'password' => 'required',
                    ], [
                        'uid.required' => '确实必要更新条件',
                        'phone.required' => '手机号码不能为空',
                        'username.required' => '用户名不能为空',
                        'gid.required' => '用户组不能为空',
                        'password.required' => '登录密码不能为空',
                    ]);

                    // 手动验证重复密码
                    if(!($userInfo['password'] == $repassword)) {
                        return Message::show(false, '两次输入密码不一致');
                    }

                    // 判断验证结构
                    if ($validate->fails()) {
                        // 验证失败
                        return Message::show(false, $validate->errors()->first());
                    }

                    // 验证通过，密码加密
                    $userInfo['password'] = Hash::make($userInfo['password']);
                }

                // 开启事务
                DB::beginTransaction();
                try {
                    // 修改数据
                    $this->userModel->where(['uid' => $userInfo['uid']])->update($userInfo);
                    // 提交数据
                    DB::commit();
                    return Message::show(true, '用户信息修改成功');
                } catch (Exception $error) {
                    // 事务回滚
                    DB::rollBack();
                    return Message::show(false, $error->getMessage());
                }
                break;
        }
    }

    /**
     * 获取用户列表
     *
     * @return void
     */
    public function query()
    {
        // 获取操作标准
        $flag = $this->request->flag;

        // switch匹配对应格式数据
        switch ($flag) {
            default:
                return Message::show(false, '未定义操作');
                break;
            case 'table':   // 获取用户列表用于后台表格展示
                // 获取分页数据
                $page = $this->request->page;
                $size = $this->request->size;
                $start  = ($page - 1) * $size;

                // 获取用户总数
                $userList['total'] = $this->userModel->count();
                $userList['page'] = (int)$page;
                $userList['size'] = (int)$size;

                // 获取当前列表数据
                $users = $this->userModel->limit($size)->skip($start)->with(['group'])->orderBy('uid', 'desc')->get();
                $userList['list'] = $users;
                return Message::show(true, '获取成功', $userList);
                break;
            case 'detail':  // 获取指定UID用户信息
                // 获取用户UID
                $uid = $this->request->uid;
                // 查询用户资料
                $userInfo = $this->userModel->where(['uid' => $uid])->first();
                return Message::show(true, '获取成功', $userInfo);
                break;
        }
    }

    public function delete()
    {
    }

    /**
     * 启用/禁用用户
     *
     * @return JsonResponse
     */
    public function status(): JsonResponse
    {
        // 获取必要参数
        $uid = $this->request->uid;
        // 获取用户信息
        $userInfo = $this->userModel->where(['uid' => $uid])->first();
        if($userInfo->gid == 1) {
            return Message::show(false, '超级管理员无法删除及禁用');
        }
        // 获取gid信息
        $info = $this->userModel->where(['uid' => $uid])->select('status')->first();
        // 开启事务
        DB::beginTransaction();
        try {
            // 修改数据库
            $this->userModel->where(['uid' => $uid])->update(['status' => $info->status == 1 ? 0 : 1]);
            // 提交事务
            DB::commit();
            return Message::show(true, $info->status == 0 ? '用户禁用成功' : '用户启用成功');
        } catch (Exception $error) {
            // 事务回滚
            DB::rollBack();
            return Message::show(false, $error->getMessage());
        }
    }
}
